package com.itcast.demoone.kotlin

fun main() {
    // mapDemo2()
    mapDemo3()
}

fun mapDemo(){
    // 1. 创建一个不可变的Map
    val list = listOf(1, 2, 3, 4, 5)
    val map = mapOf(
        "name" to "张三",
        100 to "一百",
        list to list
    )
}

fun mapDemo2(){
    // 创建不可变映射
    val countryCapitals = mapOf(
        "china" to "北京",
        "japan" to "东京",
        "france" to "巴黎"
    )

    // 访问元素
    /*println("中国首都是: ${countryCapitals["china"]}") // 输出: 北京
    println("包含法国吗? ${countryCapitals.containsKey("france")}") // 输出: true
    println("包含北京吗? ${countryCapitals.containsValue("北京s")}") // 输出: true*/

    println("国家列表: ${countryCapitals.keys}")
    println("国家首都列表: ${countryCapitals.values}")

    // 遍历键值对
    /*println("\n国家首都列表:")
    countryCapitals.forEach { (key, value) ->
        println("$key → $value")
    }*/

    // 尝试修改会报编译错误
    // countryCapitals["USA"] = "华盛顿" // 错误!
    //  countryCapitals.remove("japan")       // 错误!
}

fun mapDemo3() {
    // 1. 创建可变映射
    // 库存
    val inventory = mutableMapOf(
        "Apple" to 10,
        "Banana" to 5,
        "Orange" to 8
    )

    println("\n初始库存:")
    inventory.forEach { (item, count) -> println("$item: $count") }
    // Apple: 10  Banana: 5  Orange: 8

    // 2. 添加新商品
    inventory["Grape"] = 15  // Apple: 10  Banana: 5  Orange: 8  Grape: 15

    // 3. 修改现有商品数量
    inventory["Apple"] = 20  // Apple: 20  Banana: 5  Orange: 8  Grape: 15

    // 4. 删除商品
    inventory.remove("Banana") // Apple: 20   Orange: 8  Grape: 15

    println("\n更新后库存:")
    inventory.forEach { (item, count) -> println("$item: $count") } // Apple: 20   Orange: 8  Grape: 15

    // 5. 批量操作
    inventory.putAll(mapOf("Pear" to 7, "Peach" to 9))  // Apple: 20   Orange: 8  Grape: 15  Pear: 7  Peach: 9
    inventory -= "Orange" // 删除Orange，等价于 remove // Apple: 20     Grape: 15  Pear: 7  Peach: 9

    println("\n最终库存:")
    inventory.forEach { (item, count) -> println("$item: $count") }
}